package guigu.reflect.task230proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestAop {
	public static void main(String[] args) {
		Hunman h = new SpuerMan();
		Hunman proxy1 = (Hunman) MyProxy.getProxyInstance(h);
		proxy1.eat();
		System.out.println();
		proxy1.fly();
		System.out.println("===============");
		Subject sb = new RealSubject();
		Subject proxy2 = (Subject) MyProxy.getProxyInstance(sb);
		proxy2.action();
	}
}

interface Hunman{
	void eat();
	void fly();
}
class SpuerMan implements Hunman{
	@Override
	public void eat() {
		System.out.println("SpuerMan eat");
	}
	@Override
	public void fly() {
		System.out.println("SpuerMan fly");
	}
}
class HumanUtils{
	public static void  beforeMethod() {
		System.out.println("HumanUtils before");
	}
	public static void afterMethod() {
		System.out.println("HumanUtils afterMethod");
	}
}
class MyInvocationHanler implements InvocationHandler{
	private Object target;
	public void setTarget(Object target) {
		this.target = target;
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		HumanUtils.beforeMethod();
		Object returnVal = method.invoke(target, args);
		HumanUtils.afterMethod();
		return returnVal;
	}
}
class MyProxy{
	public  static Object getProxyInstance(Object object) {
		MyInvocationHanler mi = new MyInvocationHanler();
		mi.setTarget(object);
		return Proxy.newProxyInstance(mi.getClass().getClassLoader(), object.getClass().getInterfaces(), mi);
	}
}
